import requests
from PyQt5.QtWidgets import QWidget

import global_config
from ui.Pop_up_to_input import Pop_up_to_input
from window.My_forget_password_window import My_forget_password_window
from window.My_pop_up_warning import My_pop_up_warning


class My_pop_up_to_input(QWidget, Pop_up_to_input):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.setWindowTitle('忘记密码')

        self.pop_up_warning = My_pop_up_warning()
        self.forget_password_window = My_forget_password_window()
        self.input_username.setPlaceholderText('请输入用户名：')

        # 监听键盘输入
        self.input_username.textChanged.connect(self.update_input_username_is_none)
        # 信号与槽
        self.cancel_button.clicked.connect(self.cancel_pop_up_to_input)
        self.confirm_button.clicked.connect(self.confirm_pop_up_to_input)

    def update_input_username_is_none(self):
        if self.input_username.text() == '':
            self.input_username_is_none.setText('用户名不能为空')
        else:
            self.input_username_is_none.setText('')

    def confirm_pop_up_to_input(self):
        if self.input_username.text() == '':
            self.input_username_is_none.setText('用户名不能为空')
        else:
            url = 'http://' + global_config.localhost + ':8000/getSecurity/'
            params = {
                'username': self.input_username.text()
            }
            result = requests.get(url, params=params).json()
            if result['result'] == 'no':
                self.pop_up_warning.warning_info_label.setText('获取失败')
                self.pop_up_warning.warning_info_text.setText('没有设置密保问题')
                self.pop_up_warning.show()
            elif result['result'] == 'no-user':
                self.pop_up_warning.warning_info_label.setText('获取失败')
                self.pop_up_warning.warning_info_text.setText('用户名不存在')
                self.pop_up_warning.show()
            elif result['result'] == 'yes':
                self.forget_password_window.set_username(self.input_username.text())
                self.forget_password_window.show()
                question1 = result['que1']
                question2 = result['que2']
                self.forget_password_window.question1_text.setText(question1)
                self.forget_password_window.question2_text.setText(question2)
                self.hide()
                self.input_username.setText('')
                self.input_username_is_none.setText('')

    def cancel_pop_up_to_input(self):
        self.input_username.setText('')
        self.input_username_is_none.setText('')
        self.close()

    def closeEvent(self, event):
        self.close()
        self.pop_up_warning.close()
        self.forget_password_window.close()
        self.input_username.setText('')
        self.input_username_is_none.setText('')
